package com.hmdp.service.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.SystemConstants;
import lombok.extern.slf4j.Slf4j;
import cn.hutool.core.bean.BeanUtil;

import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
  private static final String PHONE_CAPTCHA = "code";

  @Resource
  private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result setCode(String phone, HttpSession session) {
//        校验手机号
        if(RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("手机号格式错误！");
        }
//        不符合，返回错误信息
        String code = RandomUtil.randomNumbers(6);
//        4.保存验证码到redis   set key value ex 120
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY+phone,code,LOGIN_CODE_TTL, TimeUnit.MINUTES);

        log.debug("发送短信验证码成功，验证码：{}",code);
//        返回ok
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //1.手机号和验证码是否一致？
        String phone = loginForm.getPhone();
        if(RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("手机号格式错误！");
        }

        // TODO : 3.从redis 获取验证码并校验
        String cacheCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);

        if(cacheCode == null || !cacheCode.equals(loginForm.getCode())){
          return Result.fail("验证码错误");
        }
        //一致，通过手机号查找用户
        User user = query().eq("phone", phone).one();


        //用户不存在，创建新用户
         if(user == null) {
             user = createUserWithPhone(phone);
         }

        // 7.保存用户信息到redis中

//        7.1 随机生成token,作为登录令牌
        String token = UUID.randomUUID().toString(true);
//        7.2 将User对象转为HashMap存储
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO);
        // 将 Map 中所有值的类型转换为 String
        userMap.replaceAll((k, v) -> v instanceof Long ? String.valueOf(v) : v);

// 存储到 Redis

        //7.3 存储
        String tokenKey = LOGIN_USER_KEY + token;
        stringRedisTemplate.opsForHash().putAll(tokenKey,userMap);
//        7.4设置有效期 ->只有你超过30分钟不访问，一定会踢掉
        stringRedisTemplate.expire(tokenKey,30, TimeUnit.MINUTES);

        //        8.返回token
        return Result.ok(token);
    }

    private User createUserWithPhone(String phone) {
        User user = User.builder()
                .nickName("user"+RandomUtil.randomNumbers(8))
                        .phone(phone).build();

//        保存用户
        save(user);
        return user;
    }
}
